#include "Environment.h"
#include "FileUtil.h"

namespace OCPP
{
    template<> Environment* CSingleton<Environment>::msSingleton = 0;

    Environment* Environment::getSingletonPtr(void)
    {
        return msSingleton;
    }

    Environment& Environment::getSingleton(void)
    {
        assert(msSingleton);  return (*msSingleton);
    }

	Environment::Environment(String appPath)
	{
        mAppPath = appPath;
	}

	Environment::~Environment()
	{

	}

    String Environment::getRuntimePath()
    {
#if _WIN32
#if _DEBUG
        HANDLE hDllhandle = GetModuleHandleA("OCMaind.dll");
#else
        HANDLE hDllhandle = GetModuleHandleA("OCMain.dll");
#endif
        assert(hDllhandle);

        char buff[MAX_PATH];
        memset(buff, 0, MAX_PATH);
        GetModuleFileNameA((HMODULE)hDllhandle, buff, MAX_PATH);
        String fullPath = buff;
        size_t pos = fullPath.find_last_of('\\');
        fullPath = fullPath.substr(0, pos);
        fullPath += "/";
        return StringUtil::replaceAll(fullPath, "\\", "/");
#else
        return "";
#endif
    }

    String Environment::getAppPath()
    {
        return mAppPath;
    }

    void Environment::setAppPath(String path)
    {
        mAppPath = path;
    }

    String Environment::getTmpPath()
    {
        if (mTmpPath.empty())
        {
            mTmpPath = mAppPath + "tmp/";
            FileUtil::makeDirectory(mTmpPath);
        }
        return mTmpPath;
    }

    void Environment::setTmpPath(String path)
    {
        mTmpPath = path;
    }

    void Environment::loadConfig(String fileName)
    {
        SI_Error rc = mConfig.LoadFile(fileName.c_str());
        if (rc != SI_OK)
        {
            mConfig.LoadData("[section]\nkey = value\n");
        }
    }
}
